<?php
/**
* Personal user preferences.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Config;
use Buan\SystemLog;
class PreferencesController extends ScribbleAdminController {

	/**
	* Main configuration interface.
	*
	* @param array Action parameters (none supported)
	* @return ScribbleAdminView
	*/
	public function index($params) {

		// Init
		$view = new ScribbleAdminView();
		if(!$this->init($view)) {
			return $view;
		}
		$view->setSource(Config::get('ext.Scribble.dir.views').'/scribble/preferences/index.tpl.php');
		$view->adminLanguages = Config::get('ext.Scribble.adminLanguages');
		$user = ScribbleSession::getUser();

		// Load active user's preferences
		$prefs = $user->getPreferences();

		// Process
		if(!empty($_POST)) {

			// Gather
			$prefs->set('adminLanguage', $_POST['adminLanguage']);

			// Validate
			if(!$prefs->validate()) {
				SystemLog::add('There are faults with the settings you have chosen. Please try again.', SystemLog::WARNING);
			}

			// Save: fail
			else if(!$user->getModelManager()->save($user)) {
				SystemLog::add('Failed to save preferences.', SystemLog::WARNING);
			}

			// Save: success
			else {
				SystemLog::add('Preferences have been saved successfully.', SystemLog::INFO);
				ScribbleSession::updateUser($user);

				// Set language on Views to give the user immediate feedback
				ScribbleAdminView::getGlobalView()->helpers->i18n->setLanguage($prefs->get('adminLanguage'));
				$view->helpers->i18n->setLanguage($prefs->get('adminLanguage'));
			}
		}

		// Result
		$view->prefs = $prefs;
		return $view;
	}
}
?>